# create_plugin.py
import os
import sys

def create_plugin(plugin_name):
    """创建一个自定义插件的脚手架"""

    plugins_dir = "plugins"
    plugin_dir = os.path.join(plugins_dir, plugin_name)
    c_file = os.path.join(plugin_dir, f"{plugin_name}.c")
    sconstruct_file = os.path.join(plugin_dir, "SConstruct")

    # 1. 创建插件目录
    if os.path.exists(plugin_dir):
        print(f"Error: Plugin directory '{plugin_dir}' already exists.")
        sys.exit(1)

    os.makedirs(plugin_dir)
    print(f"Created plugin directory: {plugin_dir}")

    # 2. 创建 C 文件
    with open(c_file, "w") as f:
        f.write(f"""// plugins/{plugin_name}/{plugin_name}.c
#include "plugin.h"
#include <stdio.h>
#include <stdlib.h>

// 插件信息
PluginInfo get_plugin_info_export() {{
    PluginInfo info = {{
        "{plugin_name}", // 插件名称
        "A simple {plugin_name} plugin", // 插件描述
        100 // 插件 API 版本
    }};
    return info;
}}

// 插件加载函数
bool plugin_load_export(PluginHandle* handle) {{
    printf("{plugin_name} plugin loaded.\\n");
    // 分配内存保存一些插件需要用到的数据
    int* data = (int*)malloc(sizeof(int));
    if (data == NULL) {{
        perror("Failed to allocate memory for {plugin_name} plugin data");
        return false;
    }}
    *data = 0; // 初始化数据
    *handle = (PluginHandle)data; // 使用分配的内存地址作为句柄
    return true;
}}

// 插件卸载函数
bool plugin_unload_export(PluginHandle handle) {{
    printf("{plugin_name} plugin unloaded. Handle: %p\\n", handle);
    free(handle); // 释放分配的内存
    return true;
}}

// 插件启动函数
bool plugin_start_export(PluginHandle handle) {{
    printf("{plugin_name} plugin started. Handle: %p\\n", handle);
    int* data = (int*)handle;
    printf("{plugin_name} plugin data: %d\\n", *data);

    // 插件启动时可以执行一些初始化操作
    (*data)++;
    return true;
}}

// 插件停止函数
bool plugin_stop_export(PluginHandle handle) {{
    printf("{plugin_name} plugin stopped. Handle: %p\\n", handle);
    return true;
}}
""")
    print(f"Created C file: {c_file}")

    # 3. 创建 SConstruct 文件
    with open(sconstruct_file, "w") as f:
        f.write(f"""# plugins/{plugin_name}/SConstruct
import os
from SCons.Script import *

env = Environment()

# 定义插件配置
plugin_config = {{
    "setting1": "value1",
    "setting2": 123
}}

plugin_src_files = Glob('*.c')

# 构建动态链接库 (插件)
plugin_name = os.path.splitext(os.path.basename(str(plugin_src_files[0])))[0]
plugin = env.SharedLibrary(os.path.join(build_dir, 'plugins', plugin_name), plugin_src_files, SHLIBPREFIX='')

# 返回插件对象和配置
Return(plugin=plugin, config=plugin_config)
""")
    print(f"Created SConstruct file: {sconstruct_file}")

    print(f"Plugin '{plugin_name}'脚手架创建成功.")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 create_plugin.py <plugin_name>")
        sys.exit(1)

    plugin_name = sys.argv[1]
    create_plugin(plugin_name)
